<template>
  <!-- 弹框 -->
  <a-modal
    v-if="modalConfig.visibleModal"
    v-model="modalConfig.visibleModal"
    :title="$t('pro.reports.alertModalForm.modalTitle')"
    width="650px"
    @cancel="handleClose"
  >
    <div class="text-center">
      <a-spin :spinning="dataLoading" style="position: absolute;left: 47%;top: 45%;z-index: 9999" />
      <a-form :layout="'vertical'" :form="alertForm" id="alertForm">
        <a-row>
          <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <a-form-item
              :label="$t('pro.reports.alertModalForm.labelName')"
              :wrapper-col="{ span: 23 }"
            >
              <a-input
                :placeholder="$t('pro.reports.alertModalForm.NameMess')"
                v-decorator="['alertName',{
                                        rules: [{ 
                                            required: true, 
                                            message: $t('pro.reports.alertModalForm.nameRTitle'),
                                            max: 15
                                            }]
                                        }]"
              />
            </a-form-item>
          </a-col>

          <!-- 期限 -->
          <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
            <a-form-item
              :label="$t('pro.reports.alertModalForm.labelGranularity')"
              :wrapper-col="{ span: 23 }"
            >
              <a-select
                :placeholder="$t('pro.reports.alertModalForm.TimeMess')"
                optionFilterProp="children "
                :filterOption="filterOption"
                v-decorator="['granularity',{rules: [{ required: true, message: $t('pro.reports.alertModalForm.GranularityMess') }]}]"
              >
                <a-select-option
                  v-for="item in granularityList"
                  :key="item.value"
                  :value="item.value"
                >{{ item.key }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-item
              :label="$t('pro.reports.alertModalForm.labelCampaign')"
              :wrapper-col="{ span: 24 }"
            >
              <a-select
                showSearch
                :placeholder="$t('pro.reports.alertModalForm.selectCampaigns')"
                optionFilterProp="children"
                style="width: 98%"
                :filterOption="filterOption"
                @change="campaignChange"
                v-decorator="['alertCampaign',{rules: [{ required: true, message: $t('pro.reports.alertModalForm.CampaignMess') }]}]"
              >
                <a-select-option
                  v-for="campaign in campaignsList2"
                  :key="campaign.id"
                  :value="campaign.id"
                >{{campaign.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <!-- 行为列表 -->
        <a-row
          type="flex"
          justify="space-between"
          v-for="(item, index) in alertFormRowList"
          :key="index+'key'"
        >
          <a-col span="24" style="text-align: center;margin-bottom: 8px;">
            <span
              v-show="index === 0"
              class="center-title"
              v-text="$t('pro.reports.alertModalForm.Conditions')"
            ></span>
            <div v-show="index !== 0">
              <a-form-item>
                <a-radio-group v-decorator="['boolOperation'+index,{initialValue: 'and'}]">
                  <a-radio value="and">{{$t('pro.campaignsServe.and')}}</a-radio>
                </a-radio-group>
              </a-form-item>
            </div>
          </a-col>

          <a-col
            :xs="24"
            :sm="11"
            :md="7"
            :lg="7"
            :xl="7"
            v-for="(son, index2) in item.childList"
            :key="index2+'Id'"
          >
            <a-form-item>
              <a-select
                showSearch
                optionFilterProp="children"
                :filterOption="filterOption"
                @change="campaignCondition(index,son.name+index)"
                v-decorator="[son.name+index,{rules: [{ required: true, message: $t('pro.reports.alertModalForm.OptionMess') }], initialValue:son.defaultValue}]"
              >
                <a-select-option
                  v-for="(item2, index3) in son.options"
                  :value="item2.value"
                  :key="index3+'key'"
                >{{item2.text}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xs="24" :sm="11" :md="7" :lg="7" :xl="7" class="remarks">
            <a-form-item>
              <a-input :ref="`inp`+index" v-decorator="['alertValue'+index,]"></a-input>
            </a-form-item>
            <a-icon
              type="close"
              class="h-icon-close"
              v-show="alertFormRowList.length > 1"
              @click="removeAlertFormRow(index,item.childList)"
            />
          </a-col>
        </a-row>

        <a-row type="flex" justify="start">
          <a-col span="6">
            <a-button
              type="primary"
              @click="addAlertFormRow"
              v-text="$t('pro.reports.alertModalForm.buttonLabel')"
            ></a-button>
          </a-col>
        </a-row>

        <a-row type="flex" justify="center">
          <a-col span="8" style="text-align: center;margin-bottom: 10px">
            <span class="center-title" v-text="$t('pro.reports.alertModalForm.spanActions')"></span>
          </a-col>
        </a-row>

        <a-row type="flex" justify="start">
          <a-col span="6">
            <a-form-item>
              <a-checkbox
                v-decorator="['stopCampaign', {valuePropName: 'checked' }]"
                :disabled="checkdisabled"
              >{{ $t('pro.reports.alertModalForm.stopCampaigns') }}</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col span="24">
            <a-form-item
              :label="$t('pro.reports.alertModalForm.labelAdditional')"
              :wrapper-col="{ span: 23 }"
            >
              <a-input
                v-decorator="['recipients',
                             {
                              rules: [ {
                                validator: validateToRecipients
                              }] }]"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <template slot="footer">
      <a-button
        key="submit"
        type="primary"
        html-type="submit"
        :loading="visibleLoading"
        @click="handleSubmit"
        v-text="SubmitText"
      ></a-button>
    </template>
  </a-modal>
</template>

<script>
import { addAlert, getAlert, updateAlert } from "@/api/alert-controller";
// import {getCampaignsList} from "@/api/pulldown-data"
import { mapActions } from "vuex";
import { ACTIVE, NOTACTIVE } from "@/utils/publicStatus";
import { vEmail } from "../../../utils/validate";
export default {
  name: "ModelAddAlert",
  props: {
    alertId: {
      type: Number,
      default: null
    },
    modalConfig: {
      type: Object,
      default: () => {
        return { visibleModal: false };
      }
    }
  },
  data() {
    return {
      visibleLoading: false, //弹框是否加载
      alertForm: this.$form.createForm(this),
      alertFormRowList: null, //computed ->  getAlertFormRowList
      checkdisabled: true, //表单里活动是否停止
      ACTIVE,
      NOTACTIVE,
      isNull: false, //判断警告值输入框是否禁用
      campaignsList: [],
      campaignsList2: [],
      isDisableVal: "",
      dataLoading: false //表单加载
    };
  },
  methods: {
    ...mapActions(["GetCampaignList"]),

    validateToRecipients(rule, value, callback) {
      if (value) {
        if (value.includes(",")) {
          let newArr = value.split(",");
          callback(
            newArr.every(item => {
              return vEmail(item);
            })
              ? undefined
              : this.$t("pro.loginReg.loginWra")
          );
        } else {
          callback(
            vEmail(value) ? undefined : this.$t("pro.loginReg.loginWra")
          );
        }
      } else {
        callback(undefined);
      }
    },

    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    handleClose() {
      this.alertForm.resetFields();
      let that = this;
      this.alertFormRowList.forEach(() => {
        if (that.alertFormRowList.length > 1) {
          that.alertFormRowList.pop();
        }
      });
      this.campaignsList = this.campaignsList[0];
      this.$emit("setId", 0);
    },
    // 条件选中事件 为空时让监控值为
    campaignCondition(index, value) {
      this.$nextTick(() => {
        value = this.alertForm.getFieldValue(value);
        if (value === "ISNULL") {
          this.alertForm.setFieldsValue({ [`alertValue` + index]: "0" });
          this.$refs[`inp` + index][0].$el.disabled = true;
        } else {
          this.$refs[`inp` + index][0].$el.disabled = false;
        }
      });
    },
    // campaign 选中事件 让选项禁用取消
    campaignChange(value2) {
      if (value2 !== this.campaignsList[0].id) {
        this.checkdisabled = false;
      } else {
        this.checkdisabled = true;
      }
    },
    removeAlertFormRow(index) {
      var temArray = [];
      let alertValueList = [];
      for (var i = 0; i < this.alertFormRowList.length; i++) {
        if (i != index) {
          let jsonString = JSON.stringify(this.alertFormRowList[i]);
          let list = JSON.parse(jsonString);
          let alertParametr = this.alertForm.getFieldValue("alertParametr" + i);
          let alertRelation = this.alertForm.getFieldValue("alertRelation" + i);
          let alertValue = this.alertForm.getFieldValue("alertValue" + i);
          alertValueList.push(alertValue);
          list.childList[0].defaultValue = alertParametr;
          list.childList[1].defaultValue = alertRelation;
          temArray.push(list);
        }
      }
      this.alertFormRowList = [];
      this.alertFormRowList = this.alertFormRowList.concat(temArray);
      for (var j = 0; j < temArray.length; j++) {
        this.alertForm.setFieldsValue({
          [`alertParametr` + j]: temArray[j].childList[0].defaultValue
        });
        this.alertForm.setFieldsValue({
          [`alertRelation` + j]: temArray[j].childList[1].defaultValue
        });
        this.alertForm.setFieldsValue({
          [`alertValue` + j]: alertValueList[j]
        });
      }
    },
    //添加表单里得行为行
    addAlertFormRow() {
      let RowList = this.$t("pro.reports.alertModalForm.alertFormRowList")[0];
      this.alertFormRowList.push(RowList);
      console.log(this.alertFormRowList);
    },
    //处理表单编辑提交时字段未对应
    addFlie(Arr, Fileattr, file, newFile) {
      Arr.forEach(li => {
        if (Fileattr == li[file]) {
          Fileattr = li[newFile];
        }
      });
      return Fileattr;
    },
    //处理表单提交时行为的字段
    addAlertFrom(obj, keyArr, keyStr) {
      let obj2 = { ...obj };
      let keyParametr = keyArr.filter(item => {
        if (item.substr(0, item.length - 1) == keyStr) {
          return item;
        }
      });
      let Arr = [];
      keyParametr.forEach(i => {
        Arr.push(obj2[i]);
        delete obj2[i];
      });
      obj2[keyStr] = Arr.join(",");
      return obj2;
    },
    //处理表单编辑字段对应显示
    hanleFileDisplay(Arr, value, File, newFile) {
      Arr.forEach(item => {
        if (value == item[File]) {
          value = item[newFile];
        }
      });
      return value;
    },
    //处理表单编辑按钮条件字段的显示
    handleFile(obj, flieName) {
      let obj2 = new Object();
      if (obj[flieName] !== undefined) {
        let objArr = obj[flieName].split(",");
        objArr.forEach((item, index) => {
          if (this.alertFormRowList.length < objArr.length) {
            this.alertFormRowList.push(
              this.$t("pro.reports.alertModalForm.alertFormRowList")[0]
            );
          }
          obj2[flieName + index] = item;
        });
        delete obj[flieName];
        return (obj = Object.assign(obj, obj2));
      } else {
        return obj;
      }
    },
    //表单提交按钮
    handleSubmit(e) {
      e.preventDefault();
      this.alertForm.validateFields((err, values) => {
        if (!err) {
          let obj = values;
          let keyArr = [];
          for (let [key, value] of Object.entries(obj)) {
            if (value == null) continue;
            keyArr.push(key);
          }
          let obj2 = this.addAlertFrom(values, keyArr, "alertParametr");
          let alertArr = ["alertRelation", "alertValue", "boolOperation"];
          alertArr.forEach(i => {
            obj2 = this.addAlertFrom(obj2, keyArr, i);
          });
          obj2.alertCampaign = this.addFlie(
            this.campaignsList,
            obj2.alertCampaign,
            "name",
            "id"
          );
          obj2.granularity = this.addFlie(
            this.granularityList,
            obj2.granularity,
            "key",
            "value"
          );
          obj2.stopCampaign = obj2.stopCampaign ? 1 : 0;
          const alretId = this.alertId;

          this.visibleLoading = true;
          if (alretId == null) {
            addAlert(obj2)
              .then(res => {
                if (res.data.code == "200") {
                  this.$message.success(
                    this.$t("pro.viewFilterList.add_Success"),
                    3.5
                  );
                }
              })
              .finally(() => {
                //调用父组件查询
                this.$parent.fetch();
                this.visibleLoading = false;
                this.modalConfig.visibleModal = false;
              });
          } else {
            obj2.id = alretId;
            updateAlert(obj2)
              .then(res => {
                if (res.data.code == "200") {
                  this.$message.success(
                    this.$t("pro.EditRules.EditSuccess"),
                    3.5
                  );
                }
              })
              .finally(() => {
                this.$parent.fetch();
                this.visibleLoading = false;
                this.modalConfig.visibleModal = false;
              });
          }
          this.$emit("setId", 0);
        }
      });
    }
  },
  computed: {
    granularityList() {
      return this.$t("pro.reports.alertModalForm.granularityList");
    },
    SubmitText() {
      return this.alertId == null
        ? this.$t("pro.public.buttonCreate")
        : this.$t("pro.public.buttonSave");
    },
    getcampaignsList() {
      this.campaignsList = this.$t("pro.reports.alertModalForm.campaignsList");
      return this.campaignsList;
    },
    islocale() {
      return this.$store.state.locale;
    },
    getAlertId() {
      return this.alertId;
    }
  },
  watch: {
    getAlertId(newVal) {
      this.alertId = newVal;
      if (newVal !== null) {
        this.dataLoading = true;
        let parameter = "/" + newVal;
        getAlert(parameter)
          .then(res => {
            this.alertForm = this.$form.createForm(this, {
              // 当Form.Item子节点的值发生改变时触发，可以把对应的值转存到 Redux store
              //onFieldsChange: (_, changedFields) => {},
              // 把 props 转为对应的值，可用于把 Redux store 中的值读出,可以在此给form赋值
              mapPropsToFields: () => {
                let obj = res.data.data;
                if (!obj) return;
                obj = this.handleFile(obj, "alertParametr");
                obj = this.handleFile(obj, "alertRelation");
                obj = this.handleFile(obj, "alertValue");
                obj = this.handleFile(obj, "boolOperation");
                obj.stopCampaign == 0
                  ? (obj.stopCampaign = false)
                  : (obj.stopCampaign = true);

                if (obj.alertCampaign !== 0) {
                  this.checkdisabled = false;
                }
                let data = {};
                for (let [key, value] of Object.entries(obj)) {
                  if (key == "granularity") {
                    value = value + "";
                    //value = (this.hanleFileDisplay(this.granularityList,value,'value','key'));
                  }
                  if (key === "alertCampaign") {
                    //
                  }
                  data[key] = this.$form.createFormField({ value });
                }
                console.log(data);

                return data;
              },
              // 任一表单域的值发生改变时的回调
              onValuesChange: (_, values) => {}
            });
          })
          .finally(() => {
            this.dataLoading = false;
          });
      } else {
        this.alertFormRowList.forEach((item, index) => {
          if (index !== 0) {
            this.alertFormRowList.splice(index, 1);
          }
        });
      }
    },

    "modalConfig.visibleModal": function() {
      if (this.modalConfig.visibleModal) {
        const { GetCampaignList } = this;
        GetCampaignList()
          .then(res => {
            let itme = this.getcampaignsList[0];
            this.campaignsList = [];
            this.campaignsList.push(itme);
            this.campaignsList2 = this.campaignsList.concat(res);
          })
          .catch(err => {
            console.log(err);
          });
      }
    },

    islocale(newval) {
      if (newval == "cn") {
        this.alertFormRowList = this.$t(
          "pro.reports.alertModalForm.alertFormRowList"
        );
      } else {
        this.alertFormRowList = this.$t(
          "pro.reports.alertModalForm.alertFormRowList"
        );
      }
    }
  },
  mounted() {
    this.alertFormRowList = this.$t(
      "pro.reports.alertModalForm.alertFormRowList"
    );
  }
};
</script>

<style scoped lang="less">
/*弹框*/
#alertForm {
  .remarks {
    position: relative;
    .h-icon-close {
      position: absolute;
      top: 0.5rem;
      right: -1.2rem;
      font-size: 1.2rem;
      cursor: pointer;
    }
  }
}
</style>
